﻿using System;
using System.IO;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using NhibernateClassBuilder;
using CreaMotion;

namespace CreaMotion.Forms
{
	/// <summary>
	/// Interaction logic for CreaMotionSplashForm.xaml
	/// </summary>
	public partial class LoginForm : Window
	{
        ObservableCollection<UserControls.ConnectorItem> CmbConnectionsSource = new ObservableCollection<UserControls.ConnectorItem>();

        public LoginForm()
		{
			this.InitializeComponent();
            CmbConnections.ItemsSource = CmbConnectionsSource;

            LoadSettings();

            btClose.Click += new RoutedEventHandler(btClose_Click);
            btBegin.Click += new RoutedEventHandler(btBegin_Click);
        }

        #region Show DesignForm

        void btBegin_Click(object sender, RoutedEventArgs e)
        {
            UserControls.ConnectorItem tmpObj =
                        (UserControls.ConnectorItem)CmbConnections.SelectedValue;

            Connectors.ConnectorManager.CurrentConnection =
                Connectors.ConnectorManager.GetConnector(tmpObj.Information.ConnectorName);

            try
            {
                CreaMotion.NHibernateSessionManager.NHibernateAssembly = "NhibernateClassBuilder";
                CreaMotion.NHibernateSessionManager.NHibernatenProperties=tmpObj.Settings;

                Connectors.ConnectorManager.CurrentNHibernateSession = NHibernateSessionManager.SessionFactory.OpenSession();
            }
            catch
            {
                MessageBox.Show("Please!! Check Connection Configure File.","Error!!",MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            DesignForm DF = new DesignForm();
            DF.DesignSource = Connectors.ConnectorManager.CurrentConnection.Connect();
            DF.ShowDialog();
            
            DF = null;
        }

        #endregion

        #region Close Application

        void btClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #endregion

        #region LoadSettings

        void LoadSettings()
        {
            if (!Directory.Exists(".\\Config File")) return;
            
            String[] ConfigFiles = Directory.GetFiles(".\\Config File");

            foreach (String ConfigPath in ConfigFiles)
            {
                UserControls.ConnectorItem Connector = new UserControls.ConnectorItem(ConfigPath);
                CmbConnectionsSource.Add(Connector);
            }
        }

        #endregion

    }
}